package controller

import (
	"encoding/json"
	"haiqiu-go-admin/entity/dto"
	"haiqiu-go-admin/result"
	"haiqiu-go-admin/service"
	"haiqiu-go-admin/utils"
	"log"
	"net/http"
)

// Captcha 获取验证码
func (*Api) Captcha(w http.ResponseWriter, r *http.Request) {
	captchaResponse := utils.NewCaptcha()
	result.Ok(w, r, captchaResponse)
}

// CaptchaImg 获取验证码图片
func (*Api) CaptchaImg(w http.ResponseWriter, r *http.Request) {
	log.Println("获取验证码图片..........")
	utils.ServeHTTP(w, r)
}

func (*Api) Logout(w http.ResponseWriter, r *http.Request) {
	//TODO 此处应该把token设置为无效
	utils.Token{}.SetTokenExpiration(w, r)
	result.Ok(w, r, "退出成功")
}

// SelectConfigByPrimaryKey 查询系统配置
func (*Api) SelectConfigByPrimaryKey(w http.ResponseWriter, r *http.Request) {
	sysConfig, err := service.ConfigSelectByPrimaryKey(1)
	if err != nil {
		result.Fail(w, r, err)
		return
	}
	result.Ok(w, r, sysConfig)
}

// Login 登录
func (*Api) Login(w http.ResponseWriter, r *http.Request) {
	var loginDto dto.LoginDto
	body, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		result.Fail(w, r, err)
		return
	}
	err = json.Unmarshal(body, &loginDto)
	if err != nil {
		result.Fail(w, r, err)
		return
	}
	login, err := service.Login(&loginDto)
	if err != nil {
		result.Fail(w, r, err)
		return
	}
	result.Ok(w, r, login)

}
